import traceback

from loguru import logger
from sqlalchemy import Column, Integer, String, Text, SmallInteger, ForeignKey
from sqlalchemy.orm import relationship

from database.base import BaseModel, db


class LabelModel(BaseModel):
    __tablename__ = 'blog_label'

    name = Column(String(30), nullable=False, comment='名称')
    desc = Column(String(100), nullable=True, default='', comment='描述')
    type = Column(SmallInteger, nullable=False, comment='类型,1:tag, 2:category')


# class ArticleLabelModel(BaseModel):
#     __tablename__ = 'blog_article_rel_label'
#
#     parent = relationship('ArticleModel', backref='parent')
#     child = relationship('LabelModel', backref='child')
#     type = Column(SmallInteger, nullable=False, comment='类型,1:tag, 2:category')


class ArticleModel(BaseModel):
    __tablename__ = 'blog_article'

    title = Column(String(length=50), index=True, comment='标题')
    author = Column(String(length=30), index=True, comment='作者')
    summary = Column(String(length=100), comment='摘要')
    # tag = relationship('LabelModel', backref='article')
    cover = Column(String(length=200), comment='封面')
    content = Column(Text, nullable=True, comment='内容')
    extra = relationship('ArticleExtraModel', lazy='dynamic')
    comments = relationship('CommentModel', lazy='dynamic')

    @classmethod
    def create(cls, data):
        try:
            obj = cls(**data)
            db.save(obj)
        except Exception:
            logger.error(f'save error, msg: {traceback.format_exc()}')


class ArticleExtraModel(BaseModel):

    __tablename__ = 'blog_article_extra'

    aid = Column(Integer, ForeignKey('blog_article.id'), nullable=False)
    article = relationship('ArticleModel')
    likes = Column(Integer, default=0, comment='喜欢数')
    reads = Column(Integer, default=0, comment='阅读数')
    comments = Column(Integer, default=0, comment='评论数')
    shares = Column(Integer, default=0, comment='分享数')


class CommentModel(BaseModel):
    __tablename__ = 'blog_article_comment'

    aid = Column(Integer, ForeignKey('blog_article.id'), nullable=False)
    article = relationship('ArticleModel')
    nickname = Column(String(50), nullable=False, index=True)
    email = Column(String(30), nullable=False, index=True)
    comment = Column(String(1000), nullable=False)


BaseModel.metadata.create_all(db.engine)

